package io.gitee.yaoshanli.engine.service.impl;

import io.gitee.yaoshanli.engine.db.JwDbHelper;
import io.gitee.yaoshanli.engine.service.ILinkService;
import io.gitee.yaoshanli.engine.utils.StringUtils;
import io.gitee.yaoshanli.engine.model.WfLinkModel;

public class LinkService implements ILinkService {
    @Override
    public WfLinkModel getLink(String id) {
        String sql="select * from jw_wf_link where id=?";
        Object[] args = new Object[]{id};
        return JwDbHelper.queryFirst(WfLinkModel.class,sql,args);
    }

    @Override
    public boolean remove(String id) {
        String sql="delete from jw_wf_link where id=?";
        Object[] args = new Object[]{id};
        return JwDbHelper.update(sql,args)>0;
    }

    @Override
    public boolean removeLinks(String wf_id) {
        String sql="delete from jw_wf_link where wf_id=?";
        Object[] args = new Object[]{wf_id};
        return JwDbHelper.update(sql,args)>0;
    }

    @Override
    public boolean saveOrUpdate(WfLinkModel wfLink) {
        String sql="select * from jw_wf_link where id=?";
        WfLinkModel wfLinkModel=JwDbHelper.queryFirst(WfLinkModel.class,sql,wfLink.getId());
        if(wfLinkModel!=null)
        {
            sql="update jw_wf_link wf_id =?,source_id =?,target_id =?,label =?,condition =? where id=?";
            Object args[]=new Object[]{wfLink.getWf_id(),wfLink.getSource_id(),wfLink.getTarget_id(),
                    wfLink.getLabel(),wfLink.getCondition(),wfLink.getId()};
            return JwDbHelper.update(sql,args)>0;
        }
        else
        {
            String id=wfLink.getId();
            if(StringUtils.isEmpty(id))
            {
                id=StringUtils.GUID();
            }
            sql="insert into jw_wf_link (id,wf_id,source_id,target_id,label,condition)" +
                    "        values (?,?,?,?,?,?)";
            Object args[]=new Object[]{id,wfLink.getWf_id(),wfLink.getSource_id(),wfLink.getTarget_id(),
            wfLink.getLabel(),wfLink.getCondition()};
            return JwDbHelper.update(sql,args)>0;
        }
    }

    @Override
    public WfLinkModel getPreLink(String node_id, boolean is_true) {
        String sql="select * from jw_wf_link where source_id=?";
        if(!is_true)
        {
            sql="select * from jw_wf_link where target_id=?";
        }
        WfLinkModel wfLinkModel=JwDbHelper.queryFirst(WfLinkModel.class,sql,node_id);
        return wfLinkModel;
    }
}
